//
//  LocationUpdata.m
//  ChampoinPeso
//
//  Created by mac on 2025/2/26.
//

#import "LocationUpdata.h"
#import "DataFrameParam.h"
#import <ifaddrs.h>
#import <arpa/inet.h>
#import <net/if.h>
#import <sys/sysctl.h>
#import <sys/socket.h>
#import <sys/sockio.h>
#import <sys/ioctl.h>
#import <net/if.h>
#import <arpa/inet.h>
#import <mach/mach.h>
//#import <sys/utsname.h>
#import <AFNetworking/AFNetworking.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
#import <SystemConfiguration/CaptiveNetwork.h>

@implementation LocationUpdata

+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    static LocationUpdata *instance = nil;
    dispatch_once(&onceToken,^{
        instance = [[LocationUpdata alloc] init];
        instance.lat = @"";
        instance.lot = @"";
    });
    return instance;
}


#pragma mark -beginTime-
- (void)startMarkTag {
    NSString *mark = [NSString stringWithFormat:@"%d",(int)[[NSDate date] timeIntervalSince1970]];
    [LocationUpdata sharedInstance].startMark = mark;
}


#pragma mark -Device-
- (NSDictionary *)upDataDevice {
    NSDictionary *quickness = [LocationUpdata quickness];
    NSDictionary *quavering =[LocationUpdata quavering];
    NSDictionary *inferior =[LocationUpdata inferior];
    NSDictionary *nipped =[LocationUpdata nipped];
    NSDictionary *noting =[LocationUpdata noting];
    NSDictionary *cameout =[LocationUpdata cameout];
    
    return @{@"quickness":quickness,@"quavering":quavering,@"inferior":inferior,@"nipped":nipped,@"noting":noting,@"cameout":cameout};
}


#pragma mark -quickness-
+ (NSString *)practically{
    NSURL *path = [[NSURL alloc] initFileURLWithPath:NSTemporaryDirectory()];
    NSDictionary *divide = [path resourceValuesForKeys:@[NSURLVolumeAvailableCapacityForImportantUsageKey] error:nil];
    return [NSString stringWithFormat:@"%@",divide[NSURLVolumeAvailableCapacityForImportantUsageKey]];
}

+  (NSString *)irade{
    NSURL *path = [[NSURL alloc] initFileURLWithPath:NSTemporaryDirectory()];
    NSDictionary *half = [path resourceValuesForKeys:@[NSURLVolumeTotalCapacityKey] error:nil];
    return [NSString stringWithFormat:@"%@",half[NSURLVolumeTotalCapacityKey]];
}


+ (NSString *)getAvailableMemorySize {
    vm_statistics_data_t vmStats;
    mach_msg_type_number_t infoCount = HOST_VM_INFO_COUNT;
    kern_return_t kernReturn = host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vmStats, &infoCount);
    if (kernReturn != KERN_SUCCESS) {
        return @"fail";
    }
    long long availableMemorySize = ((vm_page_size * vmStats.free_count + vm_page_size * vmStats.inactive_count));
    return [self fileSizeToString:availableMemorySize];
}

+ (NSString *)fileSizeToString:(unsigned long long)fileSize {
    NSInteger KB = 1024;
    NSInteger MB = KB*KB;
    NSInteger GB = MB*KB;
    
//    if (fileSize < 10)  {
//        return @"0 B";
//    }else if (fileSize < KB) {
//        return @"< 1 KB";
//    }else if (fileSize < MB) {
//        return [NSString stringWithFormat:@"%.2f KB",((CGFloat)fileSize)/KB];
//    }else if (fileSize < GB) {
//        return [NSString stringWithFormat:@"%.2f MB",((CGFloat)fileSize)/MB];
//    }else {
//         return [NSString stringWithFormat:@"%.2f GB",((CGFloat)fileSize)/GB];
//    }
    return [NSString stringWithFormat:@"%llu",(fileSize)];
}


+ (NSString *)far{
    unsigned long long admittedly = [NSProcessInfo processInfo].physicalMemory;
    return [NSString stringWithFormat:@"%llu",admittedly];
}

+  (NSString *)actual
{
  vm_statistics_data_t vmStats;
  mach_msg_type_number_t infoCount = HOST_VM_INFO_COUNT;
  kern_return_t kernReturn = host_statistics(mach_host_self(),
                                             HOST_VM_INFO,
                                             (host_info_t)&vmStats,
                                             &infoCount);
  
  if (kernReturn != KERN_SUCCESS) {
    return @"0";
  }
  double a = vm_page_size *vmStats.free_count;
  NSLog(@"%f",a);
  return [NSString stringWithFormat:@"%.0f",a];
}

+ (NSDictionary *)quickness {
    NSLog(@"%@ %@",[self actual],[self getAvailableMemorySize]);
    return @{@"irade":[self getNewFreeSize],@"practically":[self irade],@"far":[self getTotalMemorySize],@"actual":[self getAvailableMemorySize]};
}

+ (NSString *)getTotalMemorySize{
    long long totalMemorySize = [NSProcessInfo processInfo].physicalMemory;
    return [self fileSizeToString:totalMemorySize];
}

//+ (NSString *)getTotalDiskSize {
//    struct statfs buf;
//    unsigned long long totalDiskSize = -1;
//    if (statfs("/var", &buf) >= 0) {
//        totalDiskSize = (unsigned long long)(buf.f_bsize * buf.f_blocks);
//    }
//    return [self fileSizeToString:totalDiskSize];
//}

+ (NSString *)getNewFreeSize {

    NSError *error = nil;
        NSDictionary *results = [[[NSURL alloc] initFileURLWithPath:NSTemporaryDirectory()] resourceValuesForKeys:@[NSURLVolumeAvailableCapacityForImportantUsageKey] error:&error];
        if(error){return @"-1";}
    
        return [NSString stringWithFormat:@"%@",results[NSURLVolumeAvailableCapacityForImportantUsageKey]];
}

#pragma mark -quavering-

+ (NSDictionary *)quavering {
    [UIDevice currentDevice].batteryMonitoringEnabled = YES;
    double deviceLevel = [UIDevice currentDevice].batteryLevel * 100;
    
    NSString *unlike = @"0";
    if([UIDevice currentDevice].batteryState == UIDeviceBatteryStateCharging){
        unlike = @"1";
    }
    
    return @{@"feelingluckily":[NSString stringWithFormat:@"%d",(int)deviceLevel],@"unlike":unlike};
}

#pragma mark -inferior-
+ (NSDictionary *)inferior {
    NSString *wifem = [DataFrameParam stuck];
    NSString *office = [DataFrameParam nervous];
    NSString *trail = [DataFrameParam office];
    return @{@"wifem":wifem,@"office":office,@"trail":trail};
    
}

#pragma mark -nipped-
+ (NSDictionary *)nipped {
    NSString *wished = [self wished:[DataFrameParam nervous]];
    NSString *plum = [self plum];
    return @{@"wished":wished,@"plum":plum};
}

+ (NSString *)wished:(NSString *)useDevName {
    NSString *wished = @"0";
    if([useDevName containsString:@"Simulator"]){
        wished = @"1";
    }
    return wished;
}

+ (NSString *)plum {
    NSString *plum = @"0";
    if ([[NSFileManager defaultManager] fileExistsAtPath:@"/User/Applications/"]){
        NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:@"/User/Applications/" error:nil];
        if(files.count > 0){
            plum = @"1";
        }
    }
    return plum;
}


#pragma mark -noting-
+ (NSDictionary *)noting {
    NSString *pick = [self fixString:[NSTimeZone systemTimeZone].name];
    NSString *overbearing = [DataFrameParam even];
    NSString *ringing = [DataFrameParam armyoure];
    NSString *college = [self fixString:[[NSLocale currentLocale] objectForKey:NSLocaleLanguageCode]];
    NSString *deckmiss = [self deckmiss];
    return @{@"pick":pick,@"overbearing":overbearing,@"ringing":ringing,@"college":college,@"deckmiss":deckmiss};
}

+(NSString *)deckmiss {

    AFNetworkReachabilityStatus internetStatus = [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus;
    switch (internetStatus) {
        case AFNetworkReachabilityStatusReachableViaWiFi:
            return @"WIFI";
            break;
        case AFNetworkReachabilityStatusReachableViaWWAN:
        {
            CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
            NSString *currentStatus = info.currentRadioAccessTechnology;
            if ([currentStatus isEqualToString:CTRadioAccessTechnologyGPRS]) {
                return @"GPRS";
            }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyEdge]) {
                return @"2.75G EDGE";
            }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyWCDMA]){
                return @"3G";
            }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyHSDPA]){
                return @"3.5G HSDPA";
            }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyHSUPA]){
                return @"3.5G HSUPA";
            }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyCDMA1x]){
                return @"2G";
            }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyCDMAEVDORev0]||[currentStatus isEqualToString:CTRadioAccessTechnologyCDMAEVDORevA]||[currentStatus isEqualToString:CTRadioAccessTechnologyCDMAEVDORevB]){
                return @"3G";
            }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyeHRPD]){
                return @"HRPD";
            }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyLTE]){
                return @"4G";
            }else {
                if (@available(iOS 14.1, *)) {
                    if ([currentStatus isEqualToString:CTRadioAccessTechnologyNRNSA]){
                        return @"5G NSA";
                    }else if ([currentStatus isEqualToString:CTRadioAccessTechnologyNR]){
                        return @"5G";
                    }
                } else {
                    return @"None";
                }
            }
        }
            break;
        case AFNetworkReachabilityStatusNotReachable:
            return @"NotReachable";
        default:
            return @"Unknown";
            break;
    }
    return @"Unknown";
    
    
}


#pragma mark -cameout-

+ (NSDictionary *)cameout {
    NSMutableDictionary *clippings = [NSMutableDictionary new];
    NSArray *wifis = [self fetchSSIDInfo];
    
    if(wifis.count == 0){
        [clippings setDictionary:@{@"impoliteness":@{@"winning":@"",@"madnevertheless":@""}}];
    
    } else if(wifis.count > 0){
        
        NSMutableDictionary *definite = [NSMutableDictionary new];
        [definite setObject:wifis[0][@"SSID"] forKey:@"madnevertheless"];
        [definite setObject:wifis[0][@"BSSID"] forKey:@"winning"];
        [clippings setObject:definite forKey:@"impoliteness"];
    }
    return clippings;
}

+(NSArray *)fetchSSIDInfo{
    NSArray*ifs=(__bridge_transfer id)CNCopySupportedInterfaces();
    NSDictionary *info=nil;
    NSMutableArray *infoArr = [NSMutableArray new];
    for(NSString*ifnam in ifs){
        info=(__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        if(info&&[info count]){
            BOOL isSame = NO;
            for (int i = 0; i < infoArr.count; i++) {
                if([info[@"SSID"] isEqualToString:infoArr[i][@"SSID"]]){
                    isSame = YES;
                }
            }
            if(isSame == NO){
                [infoArr addObject:info];
            }
        }
    }
    return infoArr;
    
}





#pragma mark -Tools-
+ (NSString *)fixString:(id)obj {
    if([obj isEqual:[NSNull null]]){
        return @"";
    }
    if(obj == nil){
        return @"";
    }
    
    return [NSString stringWithFormat:@"%@",obj];
}
@end
